<template>
  <div class="md-topic-detail-pages-component">
    <!-- 头部 -->
    <MdDetailHeaderClassComponent :title="topicInfo.title" />
    <div class="md-topic-detail-panel">
      <div class="topic-item" :id="`scrollTip${key}`" v-for="(item, key) in topicInfo.content" :key="key">
        <p class="no-answer-tip" v-if="noAnswerIndexAry.includes(key)">请完成该题目</p>
        <MDTopicItemClass v-model="item.answer" :topicItemInfo="item" @clearNoAnswer="clearNoAnswer(key)"/>
      </div>
      <div class="submit-button" @click="onSubmit">提交</div>
    </div>
  </div>
</template>
<script>
import {
  getAnswerInfo,
  addAnswerRecord
} from '@/axios/topics'
import MdDetailHeaderClassComponent from '../components/class/mdDetailHeader/index.vue'
import MDTopicItemClass from '../components/class/mdTopicItem/index.vue'
export default {
  name: 'md-topic-detail-pages-component',
  components: {
    MdDetailHeaderClassComponent,
    MDTopicItemClass
  },
  data () {
    return {
      topicId: '',
      noAnswerIndex: null,
      noAnswerIndexAry: [],
      topicInfo: {
        title: '',
        grade: 0,
        content: []
      }
    }
  },
  created () {
    this.topicId = this.$route.query.topicId
    this.getAnswerInfo(this.topicId)
  },
  methods: {
    async getAnswerInfo (id) {
      const res = await getAnswerInfo(id)
      if (res.code === 200) {
        console.log(res)
        this.topicInfo = res.data
        this.topicInfo.content = JSON.parse(res.data.content).map(item => {
          return {
            ...item,
            answer: (item.topicType === 1 || item.topicType === 3) ? null : [],
            rightAnswer: +item.rightAnswer.join(),
            questionList: item.questionList.map(q => {
              return {
                ...q,
                answer: (q.topicType === 1 || q.topicType === 3) ? null : [],
                rightAnswer: +q.rightAnswer.join()
              }
            })
          }
        })
        console.log(this.topicInfo.content)
      }
    },
    // 当该题作答了，此题的“请完成该题目”的提示清除
    clearNoAnswer (key) {
      this.noAnswerIndex = null
      const cIndex = this.noAnswerIndexAry.indexOf(key)
      this.noAnswerIndexAry.splice(cIndex, 1)
    },
    async onSubmit () {
      // 一个只有答题类型和答案的数组
      const ary = this.topicInfo.content.map(item => {
        return {
          answer: item.answer,
          topicType: item.topicType
        }
      })
      // 过滤未填写项
      const filterAry = ary.filter(item => {
        if (item.topicType === 1 || item.topicType === 3) { // 单选 或 判断
          return item.answer === null
        } else if (item.topicType === 2) { // 多选
          return item.answer.length === 0
        }
      })
      // 找到所有未填写项的索引集合（未填写项给出 未作答提示）
      ary.forEach((item, index) => {
        if (item.topicType === 1 || item.topicType === 3) { // 单选 或 判断
          if (item.answer === null) {
            if (this.noAnswerIndexAry.includes(index)) return
            this.noAnswerIndexAry.push(index)
          }
        } else if (item.topicType === 2) { // 多选
          if (item.answer.length === 0) {
            if (this.noAnswerIndexAry.includes(index)) return
            this.noAnswerIndexAry.push(index)
          }
        }
      })
      // 找到未填写项中第一个未填写的索引
      this.noAnswerIndex = ary.findIndex(item => {
        if (item.topicType === 1 || item.topicType === 3) { // 单选 或 判断
          return item.answer === null
        } else if (item.topicType === 2) { // 多选
          return item.answer.length === 0
        }
      })
      // 找到未填写项中第一个未填写 的 dom
      const cDom = document.getElementById(`scrollTip${this.noAnswerIndex}`)
      // 如果存在未填写项
      if (filterAry.length > 0) {
        // 滚动到当前题目所在位置
        window.scrollTo({
          top: cDom.offsetTop - 80,
          behavior: 'smooth'
        })
        return
      }
      // 总分
      const gradeList = this.topicInfo.content.map(item => {
        if (item.questionType === 3) {
          item.questionList.map(q => {
            if ([1, 3].includes(q.topicType)) {
              if (q.answer !== q.rightAnswer) {
                q.score = 0
              } else {
                q.score = q.score || 10
              }
            }
            if (q.topicType === 2) {
              if (q.answer.length === q.rightAnswer.length) { // 多选题答案长度一致
                const flag = q.rightAnswer.every((a, i) => {
                  return a === q.answer[i]
                })
                if (!flag) { // 与正确答案不一致 不得分
                  q.score = 0
                } else { // 与正确答案一致 得分
                  q.score = q.score || 10
                }
              } else { // 多选题答案长度不一致 不得分
                q.score = 0
              }
            }
            return q
          })
        } else {
          if ([1, 3].includes(item.topicType)) {
            if (item.answer !== item.rightAnswer) {
              item.score = 0
            } else {
              item.score = item.score || 10
            }
          }
          if (item.topicType === 2) {
            if (item.answer.length === item.rightAnswer.length) { // 多选题答案长度一致
              const flag = item.rightAnswer.every((a, i) => {
                return a === item.answer[i]
              })
              if (!flag) { // 与正确答案不一致 不得分
                item.score = 0
              } else { // 与正确答案一致 得分
                item.score = item.score || 10
              }
            } else { // 多选题答案长度不一致 不得分
              item.score = 0
            }
          }
        }
        return item
      })
      console.log(this.topicInfo.content)
      let total = 0
      gradeList.forEach(item => {
        if (item.questionType === 3) {
          item.questionList.forEach(q => {
            total += q.score
          })
        } else {
          total += item.score
        }
      })
      const opts = {
        answerId: this.topicId,
        content: JSON.stringify(this.topicInfo.content),
        grade: total
      }
      console.log(opts)
      const res = await addAnswerRecord(opts)
      if (res.code === 200) {
        this.$message.success('提交成功')
        // 数据进行清空
        // this.$router.go(-1)
        this.$router.push({
          path: '/manage/datijilu'
        })
      }
    }
  }
}
</script>
<style lang="less" scoped>
.md-topic-detail-pages-component {
  width: 100%;
  padding: 30px 0;
  .md-topic-detail-panel {
    width: 1152px;
    margin: 0 auto;
    background: #fff;
    border-radius: 8px;
    padding: 20px 30px;

    // width: 100%;
    // background: #F7F8FD;
    // padding: 14px;
    // box-sizing: border-box;
    .topic-item {
      background: #FFFFFF;
      box-shadow: 0px 2px 6px 0px rgba(0,70,139,0.06);
      border-radius: 4px;
      padding: 14px;
      box-sizing: border-box;
      margin-bottom: 10px;
      &:last-child {
        margin-bottom: 0;
      }
      .no-answer-tip {
        font-size: 14px;
        font-family: SourceHanSansCN-Regular, SourceHanSansCN;
        font-weight: 400;
        color: #E73A39;
        line-height: 20px;
        margin-bottom: 6px;
      }
    }
    .submit-button {
      cursor: pointer;
      margin: 20px auto;
      width: 220px;
      height: 45px;
      border-radius: 23px;
      background: linear-gradient(180deg, #FD8663 0%, #F85332 100%);
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 15px;
      font-family: SourceHanSansCN-Medium, SourceHanSansCN;
      font-weight: bold;
      color: #FFFFFF;
      line-height: 21px;
      &:active {
        opacity: 0.9;
      }
    }
  }
}
</style>
